<?php

namespace app\sku\controller;

use think\Db;
use think\Request;

class Api
{
    public function returnData($code = 200, $msg = '成功', $data = [])
    {
        $data = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return $data;
    }

    /**
     * 添加规格值
     * */
    public function specValueCreate()
    {
        $input = Request()->param();

        $spec_id = $input['spec_id'];
        $title = $input['title'];
        $sku_key = $input['sku_key'];

        if (empty($spec_id)) return $this->returnData(0, '规格ID缺失');
        if (empty($title)) return $this->returnData(0, '请输入规格值');
        if (empty($sku_key)) return $this->returnData(0, '参数错误');

        $count = Db::name('mini_goods_sku')->where(['pid' => $spec_id, 'name' => $title, 'sku_key' => $sku_key])->count();
        if ($count) return $this->returnData(0, '规格值已存在');

        $data = [
            'pid' => $spec_id,
            'name' => $title,
            'sku_key' => $sku_key
        ];
        $id = Db::name('mini_goods_sku')->insertGetId($data);

        if ($id) {
            return $this->returnData(200, '成功', ['id' => $id]);
        } else {
            return $this->returnData(0, '失败');
        }
    }

    /**
     * 删除规格值
     * */
    public function specValueDelete()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) return $this->returnData(0, '规格值ID缺失');

        $res = Db::name('mini_goods_sku')->where(['id' => $id])->delete();
        if ($res) {
            return $this->returnData(200, '规格值删除成功');
        } else {
            return $this->returnData(0, '规格值删除失败');
        }
    }

    /**
     * 添加规格
     * */
    public function specCreate()
    {
        $input = Request()->param();

        $title = $input['title'];
        $sku_key = $input['sku_key'];

        if (empty($title)) return $this->returnData(0, '请输入规格');
        if (empty($sku_key)) return $this->returnData(0, '参数错误');

        $count = Db::name('mini_goods_sku')->where(['pid' => 0, 'name' => $title, 'sku_key' => $sku_key])->count();
        if ($count) return $this->returnData(0, '规格值已存在');

        $data = [
            'name' => $title,
            'sku_key' => $sku_key
        ];
        $id = Db::name('mini_goods_sku')->insertGetId($data);

        if ($id) {
            return $this->returnData(200, '成功', ['id' => $id]);
        } else {
            return $this->returnData(0, '失败');
        }
    }

    /**
     * 删除规格
     * */
    public function specDelete()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) return $this->returnData(0, '规格ID缺失');

        $res = Db::name('mini_goods_sku')->where(['id|pid' => $id])->delete();
        if($res){
            return $this->returnData(200, '规格删除成功');
        }else{
            return $this->returnData(0, '规格删除失败');
        }
    }
}